<?php

namespace App\Models;

use DateTimeInterface;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'openid',
        'status',
        'nickname',
        'phone',
        'password',
        'register_ip',
        'login_ip',
        'login_time',
        'unionid',
        'avatar'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * 头像地址
     */
    protected function avatar()
    {
        return Attribute::make(
            get: fn ($value) => asset($value ?? '/logo.png'),
            set: fn ($value) => normalizePath($value)
        );
    }

    /**
     * 加密密码
     */
    protected function password(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => bcrypt($value),
        );
    }

    /**
     * 获取列表数据
     * @param $params
     */
    public static function getQueryData($params = [])
    {
        return self::query()->when($params['name'] ?? '',function($query) use ($params){
            return $query->where('name','like','%'.$params['name'].'%');
        })->when($params['status'] ?? '' ,function ($query,$value){
            return $query->where('status',$value);
        })->when($params['nickname'] ?? '' ,function ($query,$value){
            return $query->where('nickname','like',"%{$value}%");
        })->when($params['phone'] ?? '' ,function ($query,$value){
            return $query->where('phone','like',"%{$value}%");
        })->latest('id')->paginate(request('pageSize',20));
    }

    /**
     * 格式化时间
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
